<?php
require_once('Model/DB.php');
require_once('Model/Prefecture.php');
require_once('Model/Validate.php');
class Model_EstateSale
{
    public function __construct()
    {
    }
    
    public function insert($data)
    {
        $db = new Model_DB();
        return $db->insert('M_ESTATE_SALE', $data);
    }
    public function update($id, $data)
    {
        $db = new Model_DB();
        return $db->update($id, 'M_ESTATE_SALE', $data);
    }
    public function get($id)
    {
        $db = new Model_DB();
        $sql = sprintf("select * from M_ESTATE_SALE where id = " . $db->escape($id) . " and enabled = 1");
        $db->query($sql);
        return $db->fetch();
    }
    public function getListCount($data)
    {
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data, 'E');
        $sql   = "select count(*) from M_ESTATE_SALE E left join D_ESTATE_SALE_IMG D on E.id = D.estate_sale_id and D.type = 1 and D.enabled = 1 WHERE E.enabled = 1";
        $sql  .= (!empty($where) ? " AND ".implode(' AND ', $where) : "");
        $db->query($sql);
        if ($db->res){
            return array_shift($res = $db->fetch());
        }
        return false;
    }
    public function getList($data, $orderby = 'E.id asc', $limit = '', $offset = '')
    {
        $list  = array();
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data, 'E');
        $sql   = "select E.*, D.filename from M_ESTATE_SALE E left join D_ESTATE_SALE_IMG D on E.id = D.estate_sale_id and D.type = 1 and D.enabled = 1 and E.enabled = 1 WHERE E.enabled = 1";
        $sql  .= (!empty($where) ? " AND ".implode(' AND ', $where) : "") . (!empty($orderby) ? " order by {$orderby}" : "") . (!empty($limit) ? " limit {$limit}" : "") . (!empty($offset) ? " offset {$offset}" : "");
        $db->query($sql);
        if ($db->res){
            while($res = $db->fetch()){
                if(isset($res['id'])){
                    $list[$res['id']] = $res;
                }
                else{
                    $list[] = $res;
                }
            }
        }
        return $list;
    }
    public function getImageList($estate_sale_id, $type = '')
    {
        $db      = new Model_DB();
        $where   = array();
        $where[] = 'enabled = 1';
        $where[] = sprintf('estate_sale_id = %d', $estate_sale_id);
        if($type != ''){
            $where[] = sprintf('type = %d', $type);
        }
        return $db->getList('D_ESTATE_SALE_IMG', $where, 'type asc, id asc');
    }
    public function getSearchList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {
        $db    = new Model_DB();
        $list  = $db->getList('M_ESTATE_SALE', $this->createSearchCondition($data), $orderby, $limit, $offset);
        return $list;
    }
    public function getReleaseList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {
        //$data['enabled'] = 1;
        //$data['status']  = 1;
        
        $where = array();
        $where[] = 'enabled = 1';
        $where[] = 'status = 1';
        $where[] = 'st_datetime <= current_timestamp';
        $where[] = 'ed_datetime > current_timestamp';
        
        $db    = new Model_DB();
        $list  = $db->getList('M_ESTATE_SALE', $where, $orderby, $limit, $offset);
        return $list;
    }
    // images
    public function insertImage($data)
    {
        $db = new Model_DB();
        return $db->insert('D_ESTATE_SALE_IMG', $data);
    }
    public function updateImage($data)
    {
        $db = new Model_DB();
        $sql = sprintf("update D_ESTATE_SALE_IMG set filename = '%s', comment = '%s' where estate_sale_id = %d and type = %d and enabled = 1", $db->escape($data['filename']), $db->escape($data['comment']), $data['estate_sale_id'], $data['type']);
        $db->query($sql); 
    }
    public function updateImageComment($data)
    {
        $db = new Model_DB();
        $sql = sprintf("update D_ESTATE_SALE_IMG set comment = '%s' where estate_sale_id = %d and type = %d and enabled = 1 and filename = '%s'", $db->escape($data['comment']), $data['estate_sale_id'], $data['type'], $db->escape($data['filename']));
        $db->query($sql); 
    }
    public function deleteImageById($id)
    {
        $db = new Model_DB();
        $sql = sprintf("update D_ESTATE_SALE_IMG set enabled = 0 where id = %d", $id);
        $db->query($sql);
    }
    
    
    //
    private function createSearchCondition($data, $prefix = '')
    {
        $db    = new Model_DB();
        $where = array();
        if ($prefix != ''){
            $prefix = $prefix . '.';
        }
        foreach($db->getFieldList('M_ESTATE_SALE') as $key => $_){
            if (isset($data[$key]) && !empty($data[$key])){
                if (is_array($data[$key])){
                    $values = array();
                    foreach ($data[$key] as $value){
                        $values[] = $db->escape($value);
                    }
                    if ($key == 'status' || $key == 'class_id' || $key == 'category_id'){
                        $w = array();
                        foreach($values as $value){
                            $w[] = "{$prefix}{$key} = '{$value}'";
                        }
                        $where[] = "(". implode(" OR ", $w) .")";
                    }
                }
                else{
                    $value = $db->escape($data[$key]);
                    if ($key == 'name'){
                        $where[] = "{$prefix}{$key} collate utf8_unicode_ci like '%{$value}%'";
                    }
                    elseif ($key == 'r_date' || $key == 'u_date'){
                        $where[] = "cast({$prefix}{$key} as date) = '{$value}'";
                    }
                    elseif ($key == 'interest'){
                        $where[] = "{$prefix}{$key} >= {$value}";
                    }
                    else{
                        $where[] = "{$prefix}{$key} = '{$value}'";
                    }
                }
            }
        }
        return $where;
    }

    public function validate(&$data, &$err)
    {
        $validate = new Model_Validate();
        // required
        $keys = explode(',', 'status,no,class_id,category_id,name,st_date');
        foreach($keys as $key){
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key]['NotEmpty'] = true;
            }
        }
        // int
        $keys = explode(',', 'price,walk_time,income,unit_price,numbers,stories,floor,management_cost,repairs_cost,rent,building_land_ratio,floor_area_ratio');
        foreach($keys as $key){
            if ($data[$key] != '' && $validate->Int($data[$key])){
                $err[$key]['Int'] = true;
            }
        }
        // float
        $keys = explode(',', 'interest,land_area,building_area');
        foreach($keys as $key){
            if ($data[$key] != '' && $validate->Float($data[$key])){
                $err[$key]['Float'] = true;
            }
        }
        // date
        $keys = explode(',', 'st_date,ed_date');
        foreach($keys as $key){
            if (isset($data[$key]) && $data[$key] != '' && $validate->Date($data[$key])){
                $err[$key]['Date'] = true;
            }
        }
        // other
        if(!isset($err['st_date']) && !isset($err['ed_date']) && $data['ed_date'] != ''){
            if($data['st_date'] > $data['ed_date']){
                $err['st_date']['Other'] = true;
            }
        }
        
        return empty($err);
    }
    
    public function getFormKeys()
    {
        $db = new Model_DB();
        return array_keys($db->getFieldList('M_ESTATE_SALE'));
    }
    //
    //　状態
    public function getStatusMap()
    {
        $map = array();
        $map[0] = '非公開';
        $map[1] = '公開';
        $map[2] = '仮登録';
        return $map;
    }
    public function getStatusName($id)
    {
        $map = $this->getStatusMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    // 種別
    public function getClassMap()
    {
        $map = array();
        $map[1] = '区分所有';
        $map[2] = '１棟売買';
        return $map;
    }
    public function getClassName($id)
    {
        $map = $this->getClassMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    // 種目
    public function getCategoryMap()
    {
        $map = array();
        $map[1]  = '中古1棟売買';
        $map[2]  = '新築1棟売買';
        $map[3]  = '中古区分所有';
        $map[4]  = '新築区分所有';
        $map[99] = 'その他';
        return $map;
    }
    public function getCategoryName($id)
    {
        $map = $this->getCategoryMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    // 特徴
    public function getSpecialMap()
    {
        $map = array();
        $map[1]  = '値下げ';
        $map[2]  = 'NEW';
        $map[3]  = '成約';
        return $map;
    }
    public function getSpecialName($id)
    {
        $map = $this->getSpecialMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    // 都道府県
    public function getPrefectureMap()
    {
        $pref = new Model_Prefecture();
        return $pref->getMap();
    }
    // 間取り
    public function getPlanMap()
    {
        $map = array();
        $map['1R']    = '1R';
        $map['1K']    = '1K';
        $map['1KD']   = '1KD';
        $map['1LKD']  = '1LDK';
        $map['2K']    = '2K';
        $map['2DK']   = '2DK';
        $map['2LDK']  = '2LDK';
        $map['その他'] = 'その他';
        return $map;
    }
    // 土地権利
    public function getRightMap()
    {
        $map = array();
        $map[1]  = '所有権';
        $map[2]  = '借地権';
        $map[99] = 'その他';
        return $map;
    }
    public function getRightName($id)
    {
        $map = $this->getRightMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    // 地目
    public function getLandCategoryMap()
    {
        $map = array();
        $map[1] = '宅地';
        $map[2] = 'その他';
        return $map;
    }
    public function getLandCategoryName($id)
    {
        $map = $this->getLandCategoryMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    // 構造
    public function getStructureMap()
    {
        $map = array();
        $map[1] = '木造';
        $map[2] = 'ＲＣ';
        return $map;
    }
    public function getStructureName($id)
    {
        $map = $this->getStructureMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    // 現況
    public function getStateMap()
    {
        $map = array();
        $map[1]  = '賃貸中';
        $map[2]  = '空室';
        $map[99] = 'その他';
        return $map;
    }
    public function getStateName($id)
    {
        $map = $this->getStateMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
?>